/*
 * @Author: evan.wan
 * @Date:   2016-06-25 15:55:20
 */

'use strict';
define([
    '../../../common/service',
    '../../../common/kit',
    'text!../tpl/fontAndDesignElement.html',
    '../../../common/ajaxfileupload'
], function(
    http,
    Kit,
    tpl
) {
    function me() {
        var self = this;
        this.init = function(templateId, templateName, templateImg, callback) {
            self.templateId = templateId;
            self.templateName = templateName;
            self.templateImg = templateImg;
            self.callback = callback;
            self.bgMainOrConcat = null;
            self.designEleTempArr = null;            //处理上传同名设计元素
            self.$root = $('#tab-content2');
            self.render();
        }

        this.render = function() {
            self.$root.html(I18N.parse(tpl, 'templateDetail'));
            self.$leftImg =  self.$root.find('.design-ele-main-img');
            self.$rightImg =  self.$root.find('.design-ele-decoration-img');
            self.event();
        }

        this.event = function() {
            //加载这个模板的字体
            self.loadFontByTemplate();
            //加载模板的 设计元素
            self.loadDesignEleByTemplate();
            //预览
            self.$root.find('.btn-add-file').off('click').on('click', $.proxy(self.btnAddFile, self));
            self.$root.find('.element-group-preview-font').off('click').on('click', $.proxy(self.openDesignPreviewDialog, self));
            self.$root.find('.btn-outline').off('click').on('click', $.proxy(self.btnOpenSelect, self));
            $('#uploadFile').change(function() {
                self.uploadFile();
            });
        }

        /**
         * 加载模板下的字体
         */
        this.loadFontByTemplate = function() {
            var param = {
                templateId: self.templateId
            }
            http.work('/ecfont/getByTmpl', param, 'POST').then(function(res) {
                if (res.succeed) {
                    _.each(res.data, function(el) {
                        self.$root.find('.tab3-title').after('<div class="font-content"><div class="font-name">' + el.fontName + '</div><div><img src="' + el.previewImg + '"></div> </div>');
                    });
                } else {
                    Kit.alert2(res.errorMsg);
                }
            });
        }

        /**
         * /加载模板的 设计元素
         */
        this.loadDesignEleByTemplate = function() {
            var param = {
                templateId: self.templateId
            }
            http.work('/ectemplatedetail/getDesignEleByTmpl', param, 'POST').then(function(res) {
                //解析模板名来渲染展示的设计元素
                var nameArr = self.templateName.split("_");
                if(nameArr[5] && nameArr[5].indexOf('3') == 0) {
                    self.bgMainOrConcat = nameArr[4];
                    var bgMainOrConcatTitle = self.$root.find('#design-ele-bg-title');
                    var mainBtn = self.$root.find('.design-ele-main .btn-outline');
                    if(self.bgMainOrConcat == 'BG01') {
                        bgMainOrConcatTitle.text(I18N.getText('templateDetail', 'mainBg'));
                        mainBtn.attr('data-type', '1')
                    } else if (self.bgMainOrConcat == 'BG02') {
                        bgMainOrConcatTitle.text(I18N.getText('templateDetail', 'spliceBg'));
                        mainBtn.attr('data-type', '2')
                    }

                    self.$root.find('.design-ele-main').removeClass('hidden');
                    self.$root.find('.design-ele-main-middle').removeClass('hidden');
                }
                if(nameArr[nameArr.length - 1].indexOf('BK') == 0){
                    self.$root.find('.design-ele-decoration').removeClass('hidden');
                }

                if (res.succeed) {
                    if(res.data.bg && res.data.bg.attachElementCode2.indexOf('3') == 0) {
                        self.$leftImg.attr('data-url', res.data.bg.attachElementImg);
                        self.$leftImg.attr('data-bgtype', res.data.bg.attachElementCode1);
                        self.$leftImg.find('.bgbk-img').attr('src', res.data.bg.attachElementImg);
                    }
                    if(res.data.bk) {
                        self.$rightImg.attr('data-url', res.data.bk.attachElementImg);
                        self.$rightImg.find('.bgbk-img').attr('src', res.data.bk.attachElementImg);
                    }
                } else {
                    Kit.alert2(res.errorMsg);
                }
            });
        }

        /**
         * 打开选择modal
         */
        this.btnOpenSelect = function(e) {
            self.openSelectDialog($(e.currentTarget).attr('data-type'));
        }

        /**
         *  主体背景和 装饰在模板上的预览
         */
        this.openDesignPreviewDialog = function() {
            self.$root.find('.dialog-main-bg-preview .templatePreview').attr('src', self.templateImg);
            self.$root.find('.dialog-main-bg-preview .templateBkPreview').attr('src', self.$rightImg.attr('data-url'));
            self.$root.find('.dialog-main-bg-preview .templateBgPreview').attr('src', self.$leftImg.attr('data-url'));
            self.$root.find(".dialog-main-bg-preview").modal('show');
        }

        /**
         * 主体背景/装饰 选择弹出
         */
        this.openSelectDialog = function(type) {
            self.$root.find('.dialog-main-bg').data('type', type);
            var modalTitle = self.$root.find('.dialog-main-bg .modal-title');
            if(type == 3)
                modalTitle.text(I18N.getText('templateDetail', 'themeDecoration'));
            else if(self.bgMainOrConcat == 'BG01')
                modalTitle.text(I18N.getText('templateDetail', 'mainBg'));
            else if (self.bgMainOrConcat == 'BG02')
                modalTitle.text(I18N.getText('templateDetail', 'spliceBg'));

            var _selectMainBgModal = self.$root.find('.dialog-main-bg');
                var param = {
                    attachElementType: type
                }
                http.work('/ecelement/getByType', param, 'POST').then(function(res) {
                    if (res.succeed) {
                        self.$root.find('.dialog-main-bg ul').empty();
                        self.designEleTempArr = [];
                        _.each(res.data, function(el) {
                            self.designEleTempArr.push(el.id);
                            self.$root.find('.dialog-main-bg ul').append('<li><div><img src="' + el.attachElementImg + '" data-id="'+el.id+'" data-code3="'+ el.attachElementCode1 +'" data-code1="'+ el.attachElementCode2 +'" ></div></li>');
                        });
                        self.$root.find('.dialog-main-bg ul li').off('click').on('click', function() {
                            $(this).addClass("active").siblings().removeClass("active");
                        });
                        _selectMainBgModal.modal("show");
                    } else {
                        Kit.alert2(res.errorMsg);
                        return false;
                    }
                });


            //保存
            _selectMainBgModal.find('button[save]').off("click").on("click", function(e) {
                var activeImg = self.$root.find('.dialog-main-bg .active img');
                if(activeImg[0]) {
                    if(type == 1){
                        self.$leftImg.find('.bgbk-img').attr('src', activeImg[0].src);
                        self.$leftImg.attr('data-url', activeImg[0].src);
                    } else if(type == 2){
                        self.$leftImg.find('.bgbk-img').attr('src', activeImg[0].src);
                        self.$leftImg.attr('data-url', activeImg[0].src);
                    } else if(type ==3) {
                        self.$rightImg.find('.bgbk-img').attr('src', activeImg[0].src);
                        self.$rightImg.attr('data-url', activeImg[0].src);
                    }
                } else {
                    Kit.alert2(I18N.getText('templateDetail', 'pleaseSelectOne'));
                    return;
                }

                var paramb = {
                    templateId: self.templateId,
                    templateName: self.templateName,
                    designCode: activeImg.attr('data-code' + (type == 3 ? 3 : 1)),
                    attachElementType: type
                }
                http.work('/ectemplatedetail/updateDesignField', paramb, 'POST').then(function(res) {
                    if (res.succeed) {
                        _selectMainBgModal.modal("hide");
                        window.localStorage.setItem('goDetailTemplateName', res.data.templateName);
                        $('.template-detail-head-name').text(res.data.templateName);
                    } else {
                        Kit.alert2(res.errorMsg);
                        return false;
                    }
                });

            });

        }




        this.btnAddFile = function(e) {
            $('#uploadFile').trigger('click');
        }

        this.uploadFile = function() {
            var formData = new FormData($('#uploadFileForm')[0]);
            $.ajax({
                url: apiUrl + "/ecelement/uploadDesignEle?bgtype=" +self.$leftImg.data('bgtype'), //server script to process data
                type: 'POST',
                cache: false,
                contentType: false,
                processData: false,
                success: function(result) {
                    if($.inArray(result.data.id, self.designEleTempArr) > -1) {
                        self.$root.find('img[data-id='+ result.data.id +']').attr('src', result.data.attachElementImg);
                    } else {
                        self.$root.find('.dialog-main-bg ul').append('<li><div><img src="' + result.data.attachElementImg + '" data-id="'+result.data.id+'" data-code3="'+ result.data.attachElementCode1 +'" data-code1="'+ result.data.attachElementCode2 +'" ></div></li>');
                    }

                    self.$root.find('.dialog-main-bg ul li').off('click').on('click', function() {
                        $(this).addClass("active").siblings().removeClass("active");
                    });
                },
                error: function(result) {
                    console.info(result);
                },
                data: formData,
                xhrFields: {
                    withCredentials: true
                }
            });
        }


    }
    return new me();
});